package com.qqhf.hitfood.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qqhf.common.entity.AjaxResult;
import com.qqhf.hitfood.bean.core.BaseController;
import com.qqhf.hitfood.bean.dto.AccountDto;
import com.qqhf.hitfood.bean.entity.AcctAdmin;
import com.qqhf.hitfood.bean.entity.AcctUser;
import com.qqhf.hitfood.service.IAcctAdminService;
import com.qqhf.hitfood.service.IAcctUserService;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

// 后台管理账号
@Api(tags = "A - 账号管理")
@RestController
@RequestMapping("/account")
public class AcctController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(AcctController.class);
    @Autowired
    private IAcctUserService acctUserService;
    @Autowired
    private IAcctAdminService acctAdminService;

    @Operation(summary = "所有账号列表")
    @GetMapping("/list")
    public AjaxResult list() {
        List<AccountDto> accountDtos = new ArrayList<>();
        List<AcctUser> acctUsers = acctUserService.list();
        List<AcctAdmin> acctAdmins = acctAdminService.list();
        accountDtos.addAll(adminToDto(acctAdmins));
        accountDtos.addAll(userToDto(acctUsers));
        return AjaxResult.success(accountDtos);
    }

    @Operation(summary = "搜索账号：账号名、分类、所属店铺")
    @GetMapping("/search")
    public AjaxResult search(
            @RequestParam(value = "shopId", required = false) Integer shopId,
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "roleId", required = false) Integer roleId) {
        List<AcctUser> acctUsers;
        List<AcctAdmin> acctAdmins;
        List<AccountDto> result = new ArrayList<>();
        if (keyword != null) {
            acctUsers = acctUserService.list(new QueryWrapper<AcctUser>().like("name", keyword));
            acctAdmins = acctAdminService.list(new QueryWrapper<AcctAdmin>().like("name", keyword));
        } else {
            acctUsers = acctUserService.list();
            acctAdmins = acctAdminService.list();
        }
        if (shopId != null) {
            acctAdmins = acctAdmins.stream().filter(item -> (item.getRoleId().equals(1) || (item.getRoleId().equals(2) && item.getShopId().equals(shopId)))).collect(Collectors.toList());
        }
        result.addAll(adminToDto(acctAdmins));
        result.addAll(userToDto(acctUsers));
        if (roleId != null) {
            result = result.stream().filter(item -> item.getRoleId().equals(roleId)).collect(Collectors.toList());
        }
        return AjaxResult.success(result);
    }

    @Operation(summary = "添加账号：账号名表范围唯一")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody AccountDto accountDto) {
        if (accountDto.getRoleId() == 1 || accountDto.getRoleId() == 2) {
            AcctAdmin name = acctAdminService.getOne(new QueryWrapper<AcctAdmin>().eq("name", accountDto.getName()), false);
            if (name == null) {
                AcctAdmin acctAdmin = new AcctAdmin();
                BeanUtils.copyProperties(accountDto, acctAdmin);
                return AjaxResult.success(acctAdminService.save(acctAdmin));
            }
            return AjaxResult.error("添加失败，该名称已存在");
        } else if (accountDto.getRoleId() == 3) {
            AcctUser name = acctUserService.getOne(new QueryWrapper<AcctUser>().eq("name", accountDto.getName()), false);
            if (name == null) {
                AcctUser acctUser = new AcctUser();
                BeanUtils.copyProperties(accountDto, acctUser);
                return AjaxResult.success(acctUserService.save(acctUser));
            }
            return AjaxResult.error("添加失败，该名称已存在");
        }
        return AjaxResult.error("添加失败，roleId出错");
    }

    @Operation(summary = "修改账号")
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody AccountDto accountDto) {
        if (accountDto.getRoleId() == 1 || accountDto.getRoleId() == 2) {
            AcctAdmin acctAdmin = new AcctAdmin();
            BeanUtils.copyProperties(accountDto, acctAdmin);
            return AjaxResult.success(acctAdminService.updateById(acctAdmin));
        } else if (accountDto.getRoleId() == 3) {
            AcctUser acctUser = new AcctUser();
            BeanUtils.copyProperties(accountDto, acctUser);
            return AjaxResult.success(acctUserService.updateById(acctUser));
        }
        return AjaxResult.error("修改失败，roleId出错");
    }

    @Operation(summary = "删除账号")
    @DeleteMapping("/delete")
    public AjaxResult delete(
            @RequestParam(value = "roleId") Integer roleId,
            @RequestParam(value = "deId") Integer deId) {
        boolean b = false;
        if (roleId == 1 || roleId == 2) {
            b = acctAdminService.removeById(deId);
        } else if (roleId == 3) {
            b = acctUserService.removeById(deId);
        }
        return AjaxResult.success(b);
    }

    @Operation(summary = "id获取账号详情")
    @GetMapping(value = "/detail")
    public AjaxResult detail(
            @RequestParam(value = "roleId") Integer roleId,
            @RequestParam(value = "id") Integer id) {
        if (roleId == 1 || roleId == 2) {
            return AjaxResult.success(adminToDto(Collections.singletonList(acctAdminService.getById(id))));
        } else if (roleId == 3) {
            return AjaxResult.success(userToDto(Collections.singletonList(acctUserService.getById(id))));
        }
        return AjaxResult.error("roleId出错");
    }

    @Operation(summary = "更新密码")
    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    public Object updatePwd(String oldPassword, String password, String rePassword) {
        try {
            if (!password.equals(rePassword)) {
                return AjaxResult.error("新密码前后不一致");
            }
//            AccountInfo accountInfo = JwtUtil.getAccountInfo();
//            if (Constants.USER_TYPE_ADMIN.equals(accountInfo.getUserType())) {
//                AcctAdmin acctAdmin = acctAdminService.get(getIdUser(HttpKit.getRequest()));
//                if (ApiConstants.ADMIN_ACCOUNT.equals(acctAdmin.getAccount())) {
//                    return AjaxResult.error("不能修改超级管理员密码");
//                }
//                logger.info("oldPassword:{},password:{},rePassword:{}", MD5.md5(oldPassword, user.getSalt()), password, rePassword);
//
//                if (!MD5.md5(oldPassword, user.getSalt()).equals(user.getPassword())) {
//                    return AjaxResult.error("旧密码输入错误");
//                }
//
//                user.setPassword(MD5.md5(password, user.getSalt()));
//                userService.update(user);
//            } else if (Constants.USER_TYPE_WAITER.equals(accountInfo.getUserType())) {
//                Shop shop = mongoRepository.findOne(Shop.class, Maps.newHashMap("name", accountInfo.getUsername(), "password", oldPassword));
//                if (shop == null) {
//                    return AjaxResult.error("旧密码输入错误");
//                }
//                if (shop.getId() != accountInfo.getUserId()) {
//                    //基本不会出现这种情况
//                    return AjaxResult.error("不允许该操作");
//                }
//                mongoRepository.update(accountInfo.getUserId(), "shops", Maps.newHashMap("password", password));
//            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return AjaxResult.error("更改密码失败");
    }

    public List<AccountDto> adminToDto(List<AcctAdmin> list) {
        System.out.println("--------------------------------------");
        System.out.println("Admin list:" + list);
        List<AccountDto> accountDtos = new LinkedList<>();
        for (int i = 0; i < list.size(); i++) {
            AcctAdmin acctAdmin = list.get(i);
            AccountDto accountDto = new AccountDto();
            BeanUtils.copyProperties(acctAdmin, accountDto);
            accountDtos.add(accountDto);
        }
        System.out.println("Dto list:" + accountDtos);
        System.out.println("--------------------------------------");
        return accountDtos;
    }

    public List<AccountDto> userToDto(List<AcctUser> list) {
        System.out.println("--------------------------------------");
        System.out.println("User list:" + list);
        List<AccountDto> accountDtos = new LinkedList<>();
        for (int i = 0; i < list.size(); i++) {
            AcctUser acctUser = list.get(i);
            AccountDto accountDto = new AccountDto();
            BeanUtils.copyProperties(acctUser, accountDto);
            accountDtos.add(accountDto);
        }
        System.out.println("Dto list:" + accountDtos);
        System.out.println("--------------------------------------");
        return accountDtos;
    }

}
